from django.shortcuts import render, redirect
# 导包
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
# 导入类视图
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
# Create your views here.
# 导入加密库
import hashlib
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
#导入json模块
import json
# 文件流
import io
#导入时间模块
import time
import datetime

#导入redis
import redis

#定义ip地址和端口
host = '127.0.0.1'
port = 6379

#生成链接对象
r = redis.Redis(host=host,port=port)

#导入models类
from myapp.models import *

#导入序列化类
from myapp.ser import *

#测试axios封装是否可以使用
class Cs(APIView):
    def get(self,request):
        uid = request.GET.get('uid')
        print(uid)

        if uid != "没有收到uid":
            res = {
                'code':200,
                'message':'测试成功'
            }
            return Response(res)
        else:
            res = {
                'code':405,
                'message':'测试失败'
            }
            return Response(res)

#创建MD5加密
def make_password(mypass):
    #生成MD5对象
    md5 = hashlib.md5()
    #定义加密对象
    sign_str = str(mypass)
    #转码
    sign_utf8 = sign_str.encode(encoding='utf-8')
    #加密
    md5.update(sign_utf8)
    #生成密钥串
    md5_server = md5.hexdigest()

    return md5_server

#手写随机验证码类
class MyCode(View):

    #定义随机颜色
    def get_random_color(self):
        R = random.randrange(255)
        G = random.randrange(255)
        B = random.randrange(255)

        return (R,G,B)

    #定义获取验证码视图
    def get(self,request):
        #定义画布
        img_size = (120,50)
        #定义画图对象
        image = Image.new('RGB',img_size,'white')
        #定义画笔对象
        draw = ImageDraw.Draw(image,'RGB')
        #定义随机字符串
        source = '0123456789'
        '''
        #定义中文随机字符串
        '''
        # source = "你好我好大家好才是真的好"
        #定义容器
        code_str = ''
        #定义字体
        my_font = ImageFont.truetype(font='C:\\Windows\\Fonts\\cambriaz.ttf',size=16)
        '''
        #定义中文字体
        '''
        #my_font = ImageFont.truetype(font='C:\\Windows\\Fonts\\msyh.ttc',size=16)
        #向容器内加入验证码
        for i in range(4):
            #获取随机颜色
            text_color = self.get_random_color()
            #获取随机字符串长度下标
            tmp_num = random.randrange(len(source))
            #获取字符集
            random_str = source[tmp_num]
            #获取到后立刻添加到容器中
            code_str += random_str
            #将字符串添加到画布
            draw.text((10+30*i,20),random_str,text_color,font=my_font)   #横纵坐标,设定的字符串,颜色
        #建立缓存区
        buf = io.BytesIO()
        #保存图片
        image.save(buf,'png')

        #将随机验证码存入redis保存
        r.set('code',code_str)

        # #将随机验证码存入dicker 环境下的redis中保存
        # docker_r.set('docker_code',code_str)

        #将随机验证码存入session中保存
        # request.session['code'] = code_str

        #返回图片并渲染
        return HttpResponse(buf.getvalue(),'image/png')

#后台管理系统注册
class Register(APIView):
    def get(self,request):
        #获取前端参数
        username = str(request.GET.get('username',None))     #用户名
        password_one = str(request.GET.get('password_one',None))     #密码
        password_two = str(request.GET.get('password_two',None))
        email  =str(request.GET.get('email',None))           #邮箱
        phone = str(request.GET.get('phone',None))           #手机号
        juris = str(request.GET.get('juris',None))           #权限
        identity = str(request.GET.get('identity',None))     #是否激活
        companies = str(request.GET.get('companies',None))   #公司信息
        code = str(request.GET.get('code',None))             #验证码

        #打印是否接收到数据
        print(
            {
                'username':username,
                'password_one':password_one,
                'password_two':password_two,
                'email':email,
                'phone':phone,
                'juris':juris,
                'identity':identity,
                'companies': companies,
                'code': code,
             }
        )

        #获取redis库内保存的验证码
        redis_code = r.get('code')
        # 进行转码操作
        redis_code = redis_code.decode('utf-8')
        # 打印查看验证码
        print("redis_code :",redis_code)

        # 判断是否正确
        if code != redis_code:
            # if code != session_code:
            res = {}
            res['code'] = 405
            res['message'] = '验证码输入错误'

            return Response(res)

        #排重
        user = User.objects.filter(username=username).first()

        #如果user存在,则代表用户名已存在,返回code405.
        if user:
            res = {}
            res['code'] = 405
            res['message'] = "用户名已存在,请更换用户名后重试"

            return Response(res)

        #如果user不存在,则代表用户名不存在,可以进行注册操作
        else:
            user = User(username=username,password=make_password(password_one),email=email,phone=phone,
                        juris_id=int(juris),creat_time=datetime.datetime,identity_id=int(identity),is_activate=0,
                        companies=int(companies))
            user.save()

            res = {}
            res['code'] = 200
            res['message'] = "注册成功,请等待管理员审核"

            return Response(res)

#登录
class Login(APIView):
    def get(self,request):
        username = str(request.GET.get('username',None))     #用户名
        password = str(request.GET.get('password',None))     #密码

        user = User.objects.filter(username=username,password=make_password(password)).first()
        if user and user.is_activate == 1:
            res = {}
            res['cdoe'] = 200
            res['message'] = '登陆成功'

            return Response(res)
        elif user and user.is_activate == 0:
            res = {}
            res['code'] = 405
            res['message'] = '登陆失败,您的账号尚未激活,请等待管理员用户激活后再登陆'
        else:
            res = {}
            res['cdoe'] = 405
            res['message'] = '登陆失败,账号或密码错误'

            return Response(res)

#查看用户信息
class Show_User(APIView):
    def get(self,request):
        username = request.GET.get('username',None)
        if username == 'admin':
            user = User.objects.filter()
            user_ser = UserSer(user, many=True).data
        else:
            user = User.objects.filter(username=username).first()
            user_ser = UserSer(user).data

        res = {}
        res['code'] = 200
        res['data'] = user_ser

        return Response(res)

#用户激活
class UpUp(APIView):
    def get(self,request):
        uid = request.GET.get('uid',None)
        user = User.objects.filter(id=uid).first()
        if user:
            user.is_activate = 1
            user.save()

        res = {}
        res['code'] = 200
        res['message'] = '账号激活成功'

        return Response(res)

#发送邮件
from . import tasks
class SendVerifyEmail(APIView):
    def get(self,request):
        username = request.GET.get('username',None)
        email = request.GET.get('email', None)
        phone = request.GET.get('phone', None)
        user = User.objects.filter(username=username).first()
        #判断用户身份
        if user and user.email == email and user.phone == phone:
            html_message = 'http://localhost:8080/?#/update_password/?username='+username+'&email='+email+'&phone='+phone
            tasks.send_email.delay(email,html_message)
            return Response({
                    'code':200,
                    'message':'邮件已发送,请前往邮箱中查看'
                 })
        else:
            return Response({
                'code': 405,
                'message': '邮件发送失败'
            })

#申请修改密码
class update_password(APIView):
    def get(self,request):
        username = request.GET.get('username',None)
        email = request.GET.get('email', None)
        phone = request.GET.get('phone', None)

        password = request.GET.get('password',None)

        user = User.objects.filter(username=username).first()
        if user and user.email == email and user.phone == phone:
            user.password = make_password(password)
            user.save()
            res = {}
            res['code'] = 200
            res['message'] = "修改成功"

            return Response(res)

        else:
            res = {}
            res['code'] = 405
            res['message'] = "修改失败"

            return Response(res)

#编辑用户权限
class Update_Qx(APIView):
    def get(self,request):
        uid = request.GET.get('uid',None)
        username = request.GET.get('username',None)
        juros_id = request.GET.get('juros_id',None)
        identity_id = request.GET.get('identity_id',None)
        #查库获取要修改的用户
        user = User.objects.filter(id=uid,username=username).first()
        #如果user存在,进行修改
        if user:
            user.juris_id = juros_id
            user.identity_id = identity_id
            user.save()

            res = {}
            res['code'] = 200
            res['message'] = "修改用户权限成功"

            return Response(res)
        else:
            res = {}
            res['code'] = 405
            res['message'] = "修改用户权限失败"

            return Response(res)

#公司信息展示
class Companies_Info(APIView):
    def get(self,request):
        username = request.GET.get('username',None)
        user = User.objects.filter(username=username).first()
        if user:
            companies = Companies.objects.filter(id=user.companies).first()
            companies_ser = CompaniesSer(companies).data

            res = {}
            res['cdoe'] = 200
            res['data'] = companies_ser

            return Response(res)
        else:
            res = {}
            res['cdoe'] = 405
            res['message'] = '获取信息失败'

            return Response(res)

#获取标签信息
class Get_Tag(APIView):
    def get(self,request):
        save_id = request.GET.get('save_id',None)
        if save_id == None:
            tags = Tags.objects.filter()
            tags_ser = TagsSer(tags,many=True).data

            res = {}
            res['code'] = 200
            res['data'] = tags_ser

            return Response(res)
        elif save_id == str(1):
            tags = Tags.objects.filter(is_save=save_id)
            tags_ser = TagsSer(tags,many=True).data

            res = {}
            res['code'] = 200
            res['data'] = tags_ser

            return Response(res)
        else:
            tags = Tags.objects.filter(is_save=0)
            tags_ser = TagsSer(tags, many=True).data

            res = {}
            res['code'] = 200
            res['data'] = tags_ser

            return Response(res)

#获取货物类型
class E_type(APIView):
    def get(self,request):
        cargotype = CargoType.objects.filter()
        cargotype_ser = CargoTypeSer(cargotype,many=True).data

        res = {}
        res['code'] = 200
        res['data'] = cargotype_ser

        return Response(res)

#添加标签
class Add_Tags(APIView):
    def get(self,request):
        tag_id = request.GET.get('tags_id',None)
        c_type = request.GET.get('c_type',None)
        create_user = int(request.GET.get('create_user',None))
        user_id = int(request.GET.get('user_id',None))

        tags = Tags.objects.filter(tag_id=tag_id).first()
        if tags:
            return Response(
                {
                    'code':405,
                    'message':'标签已存在,请勿重复添加'
                }
            )
        else:
            tags = Tags(tag_id=str(tag_id),cargo_name=str(c_type),creator=int(create_user),assigner=int(user_id),is_save=int(0))
            tags.save()
            return Response(
                {
                    'code': 200,
                    'message': '标签添加成功,请返回原页面查看'
                }
            )

    def post(self,request):
        id = request.data.get('id',None)
        tagid = request.data.get('tags_id', None)
        c_type = request.data.get('c_type', None)
        user_id = int(request.data.get('user_id', None))
        print(id,tagid,c_type,user_id)

        tags = Tags.objects.filter(id=id).first()
        tags.tag_id = tagid
        tags.cargo_name = c_type
        tags.assigner = user_id
        tags.save()

        return Response(
            {
                'code': 200,
                'message': '标签修改成功,请刷新页面查看'
            }
        )

    def delete(self,request):
        pass

#添加货物类型
class Add_CType(APIView):
    def get(self,request):
        username = request.GET.get('username',None)
        name = request.GET.get('name',None)     #货物名称
        time = request.GET.get('time',None)     #延迟开始
        desc = request.GET.get('desc',None)     #描述
        gap = request.GET.get('gap',None)       #记录间隔
        gap1 = request.GET.get('gap1',None)     #理想温度范围1
        gap2 = request.GET.get('gap2',None)     #理想温度范围2
        alarm_1 = json.loads(request.GET.get('alarm_1',None))
        alarm_2 = json.loads(request.GET.get('alarm_2',None))
        alarm_3 = json.loads(request.GET.get('alarm_3',None))
        alarm_4 = json.loads(request.GET.get('alarm_4',None))
        alarm_5 = json.loads(request.GET.get('alarm_5',None))
        alarm_6 = json.loads(request.GET.get('alarm_6',None))

        range_list = []
        range_list.append(gap1)
        range_list.append(gap2)

        police_list = []        #报警类型列表,储存六种报警类型的数据
        police_list.append(alarm_1)
        police_list.append(alarm_2)
        police_list.append(alarm_3)
        police_list.append(alarm_4)
        police_list.append(alarm_5)
        police_list.append(alarm_6)

        print(police_list)

        cargo = CargoType.objects.filter(name=name).first()
        if cargo:
            return Response(
                {
                    'code':405,
                    'message':'该货物类型已存在,请勿重复添加'
                }
            )
        else:
            cargo = CargoType(name=name,desc=desc,delayed_time=time,inter_record=gap,
                              temp_range=json.dumps(range_list),alarm_set=json.dumps(police_list),
                              companies=User.objects.filter(username=username).first().companies)
            cargo.save()
            return Response(
                {
                    'code': 200,
                    'message': '货物类型添加成功'
                }
            )